<?php

namespace App\Containers\AppSection\Profile\Actions;

use App\Containers\AppSection\BankDetail\Tasks\CreateDefaultBankDetailTask;
use App\Containers\AppSection\Data\Tasks\CreateDefaultCompanyTask;
use App\Containers\AppSection\Data\Tasks\CreateDefaultPassportTask;
use App\Containers\AppSection\Data\Tasks\CreateDefaultPersonalTask;
use App\Containers\AppSection\LegalForm\Tasks\CreateDefaultLegalFormTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Data\Repositories\ProfileRepository;
use App\Containers\AppSection\Profile\Models\Profile;
use App\Containers\AppSection\Profile\Tasks\CreateProfileTask;
use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\Profile\UI\API\Requests\CreateOuterProfileRequest;
use App\Containers\AppSection\Questionnaire\Tasks\CreateDefaultQuestionnairesTask;
use App\Ship\Criterias\OrderByCreationDateAscendingCriteria;
use App\Ship\Criterias\ThisUserCriteria;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Exceptions\Exception;
use Auth;

class CreateOuterProfileAction extends Action
{
    protected ProfileRepository $repository;

    public function __construct(ProfileRepository $repository)
    {
        $this->repository = $repository;
    }

    public function run(CreateOuterProfileRequest $request): Profile
    {
        try {
            $profile = $this->repository
                ->pushCriteria(new OrderByCreationDateAscendingCriteria())
                ->pushCriteria(new ThisUserCriteria())
                ->findWhere([['accreditation_status_key', '=', 'accreditation_accredited']])
                ->first();
            if (empty($profile))
                throw new NotFoundException(__('ship::resource.not-found'));

        } catch (Exception $e) {
            $profile = app(FindLatestProfileByUserIdTask::class)->run(Auth::id());
        }

        //Создание данных
        $fio = $request['fio'] ?? $profile->legal_form->personal->fio ?? Auth::user()->name;
        $withoutPatronymic = $profile->legal_form->personal->without_patronymic ?? false;
        $passport = app(CreateDefaultPassportTask::class)->run(Auth::id());
        $personal = app(CreateDefaultPersonalTask::class)->run(Auth::id(), $fio, $withoutPatronymic);

        $companyId = null;
        if ($request->getInputByKey('legal_form_type') === 'entity') {
            $company = app(CreateDefaultCompanyTask::class)->run(Auth::id(), $request->getInputByKey('company_name'));
            $companyId = $company->id;
        }

        //Создание правовой формы
        $legalForm = app(CreateDefaultLegalFormTask::class)->run(Auth::id(), $passport->id, $personal->id, $companyId);

        //Создание анкеты
        app(CreateDefaultQuestionnairesTask::class)
            ->run($request->getInputByKey('legal_form_type'), $legalForm->id);

        //Создание профиля
        $profileNew = app(CreateProfileTask::class)
            ->run([
                'user_id' => Auth::id(),
                'phone' => $profile->phone,
                'legal_form_type' => $request->getInputByKey('legal_form_type'),
                'legal_form_id' => $legalForm->id,
            ]);

        //Создание банковских реквизитов
        app(CreateDefaultBankDetailTask::class)->run($profileNew->id);


        app(CreateLogTask::class)->run($profile->id, 'Создание нового профиля', 'profile');

        return $profileNew;
    }
}
